<template>
	<view class="edit-bg">
		<!-- 头像+进度 -->
		<view class="avatar-progress-box">
			<view class="progress-ring">
				<u-circle-progress :percent="profilePercent" :width="220" :border-width="12" active-color="#23264d"
					bg-color="#23232b" :text="false">
					<view class="avatar-wrap" @click.stop="chooseAvatar">
						<!-- <u-avatar :src="globalConfig.site_url+form.image" :size="avatarSize" shape="circle" /> -->
						<image :src="globalConfig.site_url+form.image" style="width: 230rpx;height: 230rpx;" />
						<view class="avatar-upload">
							<u-icon name="camera" size="36" color="#fff" />
						</view>
					</view>
				</u-circle-progress>
				<text class="percent-text">{{ profilePercent }}%</text>
			</view>
			<view class="progress-tip" v-if="globalConfig.examine != 1">资料完整程度越高，遇见优质搭子概率越高哦</view>
		</view>
		<!-- 个人照片 -->
		<view class="section-title">
			个人照片<text class="photo-count">({{ form.images.length }}/9)</text>
			<text class="score-tip">+20%</text>
		</view>
		<view class="photo-upload-box">
			<view class="photo-add" @click="chooseImage">
				<u-icon name="plus" size="48" color="#888" />
			</view>
			<view class="photo-item" v-for="(img, index) in form.images" :key="index">
				<!-- 刪除 -->
				<view class="photo-delete" @click="deleteImage(index)" :key="index">
					<u-icon name="trash" size="20" color="#fff" />
				</view>
				<image :src="globalConfig.site_url+img" class="photo-thumb" />
			</view>
		</view>
		<!-- 个人简介 -->
		<view class="section-title">
			个人简介
			<text class="score-tip">+20%</text>
		</view>
		<!-- 我的标签 -->
		<view class="section-title">
			我的标签
			<text class="score-tip">+30%</text>
		</view>
		<view class="tag-box" @click="showTagPopup = true">
			<view v-if="selectedTags.length === 0" class="tag-placeholder">点击选择标签</view>
			<view v-else class="tag-list">
				<view v-for="tag in selectedTags" :key="tag.id" class="tag-selected">{{ tag.name }}</view>
			</view>
		</view>
		<!-- 微信号 -->
		<view class="section-title">
			微信号
			<text class="wx-tip" v-if="globalConfig.examine != 1">让属于您的灵魂搭子们不再错过您</text>
			<text class="score-tip">+30%</text>
		</view>
		<view class="wx-input-box" @click="showWxPopup = true">
			<u-icon name="weixin-fill" size="36" color="#7bdffe" />
			<text class="wx-value">{{ form.wechat ? form.wechat : '点击填写微信号' }}</text>
		</view>
		<!-- 基础信息 -->
		<view class="section-title">
			基础信息
			<text class="score-tip">+20%</text>
		</view>
		<view class="base-info-box">
			<view class="base-row" @click="editField('nickname')">
				<text class="base-label">昵称</text>
				<view class="base-value">{{ form.nickname || '未填写' }}</view>
				<u-icon name="arrow-right" size="20" color="#888" />
			</view>
			<view class="base-row" @click="editField('gender')">
				<text class="base-label">性别</text>
				<view class="base-value">{{ genderText }}</view>
				<u-icon name="arrow-right" size="20" color="#888" />
			</view>
			<view class="base-row">
				<text class="base-label">生日</text>
				<view class="base-value">
					<picker mode="date" :value="form.birthday" @change="onBirthdayChange">
						<view class="base-value">{{ form.birthday || '未填写' }}</view>
					</picker>
				</view>
				<u-icon name="arrow-right" size="20" color="#888" />
			</view>
			<view class="base-row" @click="editField('phone')">
				<text class="base-label">手机号</text>
				<view class="base-value">{{ form.phone || '未填写' }}</view>
				<u-icon name="arrow-right" size="20" color="#888" />
			</view>
			<view class="base-row" @click="editField('signature')">
				<text class="base-label">个性签名</text>
				<view class="base-value">{{ form.signature || '未填写' }}</view>
				<u-icon name="arrow-right" size="20" color="#888" />
			</view>
		</view>
		<!-- 保存按钮 -->
		<view class="save-btn-box">
			<u-button type="primary" shape="circle" @click="submit">保存</u-button>
		</view>
		<!-- 标签弹窗 -->
		<u-popup v-model="showTagPopup" mode="center" border-radius="24" :mask-close-able="true">
			<view class="popup-content">
				<view class="popup-title">选择标签（最多8个）</view>
				<view class="popup-tags">
					<view v-for="tag in tagOptions" :key="tag.id"
						:class="['popup-tag', selectedTags.some(t => t.id === tag.id) ? 'selected' : '']"
						@click="toggleTag(tag)">{{
              tag.name }}</view>
				</view>
				<u-button type="primary" shape="circle" @click="showTagPopup = false">完成</u-button>
			</view>
		</u-popup>
		<!-- 微信号弹窗 -->
		<u-popup v-model="showWxPopup" mode="center" border-radius="24" :mask-close-able="true">
			<view class="popup-content">
				<view class="popup-title">填写微信号</view>
				<u-input v-model="form.wechat" placeholder="请输入微信号" border="none"
					style="background-color: #fff !important;" />
				<u-button type="primary" shape="circle" @click="showWxPopup = false">确定</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getUserInfo,
		updateUserInfo,
		getUserTags
	} from '@/api/user.js' // 假设你的接口
	import {
		mapGetters,
		mapActions,
		mapState
	} from 'vuex';
	import request from '@/common/request.js'
	export default {
		name: 'EditProfile',
		data() {
			return {
				form: {
					image: '',
					images: [],
					wechat: '',
					nickname: '',
					gender: '', // 1男 2女
					birthday: '',
					phone: '',
					signature: ''
				},
				tagOptions: [],
				selectedTags: [],
				pendingTagIds: null,
				showTagPopup: false,
				showWxPopup: false,
				avatarSize: '50vw'
			}
		},
		computed: {
			profilePercent() {
				let percent = 0;
				if (this.form.image) percent += 10;
				if (this.form.images && this.form.images.length > 0) percent += 20;
				if (this.selectedTags.length > 0) percent += 30;
				if (this.form.wechat) percent += 30;
				if (this.form.nickname && this.form.gender) percent += 10;
				return Math.min(percent, 100);
			},
			genderText() {
				if (this.form.gender === '1') return '男';
				if (this.form.gender === '2') return '女';
				return '未填写';
			},
			// 使用mapState直接访问state
			...mapState({
				globalConfig: state => state.config,
				userLocation: state => state.location,
			})
		},
		onShow() {
			this.loadUserInfo();
			this.loadTags();
		},
		methods: {
			// 头像选择
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					sizeType: ['compressed'],
					success: (res) => {
						console.log('图片选择成功:', res);
						if (res.tempFilePaths && res.tempFilePaths.length > 0) {
							const tempPath = res.tempFilePaths[0];
							this.form.image = this.uploadAvatar(tempPath);
						} else {
							console.error('未找到选择的图片路径', res);
							this.$u.toast('获取图片路径失败');
						}
					},
					fail: (err) => {
						console.error('图片选择失败:', err);
						this.$u.toast('选择图片失败');
					}
				});
			},
			// 上传头像
			async uploadAvatar(filePath) {
				console.log('准备上传的文件路径:', filePath);
				uni.showLoading({
					title: '上传中...'
				});
				try {
					// 步骤1: 使用 uni.uploadFile 上传文件
					const uploadResult = await new Promise((resolve, reject) => {
						uni.uploadFile({
							url: request.baseUrl + '/api/user/upload',
							filePath: filePath,
							name: 'file',
							header: {
								token: uni.getStorageSync('token')
							},
							success: (uploadRes) => {
								const data = JSON.parse(uploadRes.data);
								if (uploadRes.statusCode === 200 && data.code === 1) {
									resolve(data);
								} else {
									reject(new Error(data.msg || '服务器上传失败'));
								}
							},
							fail: (err) => {
								reject(new Error('网络请求失败，请检查网络连接'));
							}
						});
					});

					// 步骤2: 更新用户头像信息
					this.form.image = uploadResult.data.image;
					// const updateResult = await updateUserInfo({ image: this.form.image });
					// if (updateResult.code !== 1) {
					// 	throw new Error(updateResult.msg || '更新用户信息失败');
					// }

					// 步骤3: 更新全局状态
					// this.$store.commit('UPDATE_USER_INFO', { image: this.form.image });
					// this.$u.toast('头像更新成功');
				} catch (error) {
					console.error('头像上传失败:', error);
					this.$u.toast(error.message || '操作失败');
				} finally {
					uni.hideLoading();
				}
			},
			chooseImage() {
				uni.chooseImage({
					count: 9 - this.form.images.length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						uni.showLoading({
							title: '上传中...'
						});
						const uploadPromises = res.tempFilePaths.map(tempPath => {
							return new Promise((resolve, reject) => {
								uni.uploadFile({
									url: request.baseUrl + '/api/user/upload',
									filePath: tempPath,
									name: 'file',
									header: {
										token: uni.getStorageSync('token')
									},
									success: (uploadRes) => {
										const data = JSON.parse(uploadRes.data);
										console.log(data, 'image');
										if (uploadRes.statusCode === 200 && data
											.code === 1) {
											resolve(data.data.image);
										} else {
											reject(new Error(data.msg ||
												'图片上传失败'));
										}
									},
									fail: (err) => {
										reject(new Error('网络请求失败'));
									}
								});
							});
						});

						Promise.all(uploadPromises)
							.then(urls => {
								console.log(urls);
								this.form.images = [...this.form.images, ...urls];
								this.$u.toast('照片上传成功');
							})
							.catch(error => {
								console.error('照片上传失败:', error);
								this.$u.toast(error.message || '照片上传失败');
							})
							.finally(() => {
								uni.hideLoading();
							});
					}
				});
			},
			onBirthdayChange(e) {
				this.form.birthday = e.detail.value;
			},
			editField(field) {
				if (field === 'nickname') {
					uni.showModal({
						title: '修改昵称',
						editable: true,
						placeholderText: '请输入昵称',
						success: res => {
							if (res.confirm && res.content) this.form.nickname = res.content;
						}
					});
				}
				if (field === 'gender') {
					uni.showActionSheet({
						itemList: ['男', '女'],
						success: res => {
							this.form.gender = res.tapIndex === 0 ? '1' : '2';
						}
					});
				}
				if (field === 'phone') {
					uni.showModal({
						title: '修改手机号',
						editable: true,
						placeholderText: '请输入手机号',
						success: res => {
							if (res.confirm && res.content) this.form.phone = res.content;
						}
					});
				}
				if (field === 'signature') {
					uni.showModal({
						title: '个性签名',
						editable: true,
						placeholderText: '请输入个性签名',
						success: res => {
							if (res.confirm && res.content) this.form.signature = res.content;
						}
					});
				}
			},
			async loadUserInfo() {
				try {
					const res = await getUserInfo();
					console.log(res, 'getUserInfo response');

					if (res && res.code == 1) {
						const d = res.data || {};
						this.form.nickname = d.nickname || '';
						this.form.image = d.image || '';
						this.form.gender = d.gender || '';
						this.form.signature = d.signature || '';
						this.form.birthday = d.birthdaytime || '';
						this.form.phone = d.phone || '';
						this.form.wechat = d.wx_sn || '';
						this.form.images = Array.isArray(d.images) ? d.images.filter(i => i) : [];
						// tag_ids 可能为字符串或数组
						// 处理标签回显
						if (d.tag_ids) {
							const ids = String(d.tag_ids).split(',').filter(Boolean);
							if (this.tagOptions.length > 0) {
								// 当标签列表已加载时直接匹配
								this.selectedTags = this.tagOptions.filter(tag => ids.includes(String(tag.id)));
							} else {
								// 当标签列表未加载时先保存ID，等标签加载后再匹配
								this.pendingTagIds = ids;
							}
						} else if (d.tags && Array.isArray(d.tags)) {
							// 兼容旧格式：直接使用完整标签信息
							this.selectedTags = d.tags.map(t => ({
								id: t.id,
								name: t.name
							}));
						} else {
							this.selectedTags = [];
						}
					}
				} catch (e) {
					console.log(e, '获取个人信息失败');

					uni.showToast({
						title: '获取个人信息失败',
						icon: 'none'
					});
				}
			},
			async loadTags() {
				try {
					const res = await getUserTags();
					// res.data.data 是 [{id, name}, ...]
					if (res && res.data.code == 1 && Array.isArray(res.data.data)) {
						this.tagOptions = res.data.data; // 直接赋值为一维数组
						// 处理延迟的标签ID匹配
						if (this.pendingTagIds && this.pendingTagIds.length > 0) {
							this.selectedTags = this.tagOptions.filter(tag =>
								this.pendingTagIds.includes(String(tag.id))
							);
							this.pendingTagIds = null;
						}
					}
				} catch (e) {
					uni.showToast({
						title: '标签获取失败',
						icon: 'none'
					});
				}
			},
			toggleTag(tag) {
				const idx = this.selectedTags.findIndex(t => t.id === tag.id);
				if (idx > -1) {
					this.selectedTags.splice(idx, 1);
				} else if (this.selectedTags.length < 8) {
					this.selectedTags.push(tag);
				} else {
					uni.showToast({
						title: '最多选择8个标签',
						icon: 'none'
					});
				}
			},
			async submit() {
				// 校验
				if (!this.form.nickname) {
					uni.showToast({
						title: '请填写昵称',
						icon: 'none'
					});
					return;
				}
				if (!this.form.gender) {
					uni.showToast({
						title: '请选择性别',
						icon: 'none'
					});
					return;
				}
				// tag_ids 用id拼接
				const tag_ids = this.selectedTags.map(t => t.id).join(',');
				console.log(tag_ids, 'tag_ids');
				console.log(this.userLocation);
				// 这里假设你有全局经纬度
				const long = this.userLocation.longitude || '';
				const lat = this.userLocation.latitude || '';
				// 生日字段名为 birthdaytime
				const params = {
					nickname: this.form.nickname,
					image: this.form.image,
					images: this.form.images,
					gender: this.form.gender,
					signature: this.form.signature,
					birthdaytime: this.form.birthday,
					phone: this.form.phone,
					wx_sn: this.form.wechat,
					tag_ids,
					long,
					lat
				};
				try {
					const res = await updateUserInfo(params); // 你的GET接口
					console.log(res, 'updateUserInfo response');
					if (res.data.code !== 1) {
						uni.showToast({
							title: res.data.msg || '保存失败',
							icon: 'none'
						});
						return;
					}
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					});
					setTimeout(() => uni.navigateBack(), 800);
				} catch (e) {
					console.log(e, 'e');

					uni.showToast({
						title: '保存失败',
						e
					});
				}
			},
			deleteImage(index) {
				this.form.images.splice(index, 1);
			}
		}
	}
</script>

<style scoped>
	.edit-bg {
		min-height: 100vh;
		background: #18181a;
		color: #fff;
		padding-bottom: 64rpx;
	}

	.top-bar {
		display: flex;
		align-items: center;
		padding: 32rpx 0 32rpx 32rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		margin-left: 24rpx;
		color: #fff;
	}

	.avatar-progress-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 24rpx;
	}

	.progress-ring {
		position: relative;
		width: 220rpx;
		height: 220rpx;
		margin-bottom: 16rpx;
	}

	.percent-text {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 12rpx;
		text-align: center;
		width: 100%;
		color: #fff;
		font-size: 28rpx;
		font-weight: bold;
	}

	.progress-tip {
		color: #b0b0b0;
		font-size: 24rpx;
		margin-bottom: 24rpx;
		text-align: center;
	}

	.section-title {
		margin: 32rpx 32rpx 12rpx 32rpx;
		font-size: 28rpx;
		font-weight: bold;
		display: flex;
		align-items: center;
		color: #fff;
		position: relative;
	}

	.photo-count {
		font-size: 22rpx;
		color: #b0b0b0;
		margin-left: 12rpx;
	}

	.score-tip {
		font-size: 20rpx;
		color: #b0b0b0;
		margin-left: auto;
	}

	.photo-upload-box {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		margin: 0 32rpx 12rpx 32rpx;
		min-height: 160rpx;
	}

	.photo-item {
		position: relative;
	}

	.photo-delete {
		position: absolute;
		width: 32rpx;
		height: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		top: -16rpx;
		right: -16rpx;
		border-radius: 50%;
		z-index: 10;
		border: 1px solid #fff;
	}

	.photo-add {
		width: 140rpx;
		height: 140rpx;
		border: 2rpx dashed #444;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #23232b;
	}

	.photo-thumb {
		width: 140rpx;
		height: 140rpx;
		border-radius: 16rpx;
		object-fit: cover;
		background: #23232b;
	}

	.tag-box {
		margin: 0 32rpx 12rpx 32rpx;
		background: #23232b;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, 0.12);
		min-height: 80rpx;
		display: flex;
		align-items: center;
		padding: 0 24rpx;
		position: relative;
		cursor: pointer;
	}

	.tag-placeholder {
		color: #888;
		font-size: 28rpx;
	}

	.tag-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		align-items: center;
	}

	.tag-selected {
		background: #18181a;
		border: 1rpx solid #888;
		border-radius: 32rpx;
		padding: 8rpx 28rpx;
		color: #fff;
		font-size: 26rpx;
	}

	.wx-tip {
		font-size: 20rpx;
		margin-left: 16rpx;
		background: linear-gradient(90deg, #ffb6e8, #ff8dd3, #ffc494, #ffa970);
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
	}

	.wx-input-box {
		margin: 0 32rpx 12rpx 32rpx;
		background: #23232b;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, 0.12);
		display: flex;
		align-items: center;
		padding: 0 24rpx;
		min-height: 80rpx;
		cursor: pointer;
	}

	.wx-input {
		flex: 1;
		color: #fff;
		margin-left: 12rpx;
	}

	.base-info-box {
		margin: 0 32rpx 12rpx 32rpx;
		background: #23232b;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, 0.12);
		overflow: hidden;
	}

	.base-row {
		display: flex;
		align-items: center;
		padding: 32rpx 24rpx;
		border-bottom: 1rpx solid #222;
		position: relative;
	}

	.base-row:last-child {
		border-bottom: none;
	}

	.base-label {
		font-size: 28rpx;
		color: #b0b0b0;
		width: 140rpx;
	}

	.base-value {
		flex: 1;
		color: #fff;
		font-size: 28rpx;
	}

	.save-btn-box {
		margin: 48rpx 32rpx;
		display: flex;
		justify-content: center;
	}

	.tag-edit-bg {
		min-height: 100vh;
		background: #18181a;
		color: #fff;
		padding-bottom: 64rpx;
	}

	.tag-card {
		margin: 32rpx;
		background: #23232b;
		border-radius: 24rpx;
		min-height: 160rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, 0.12);
		position: relative;
	}

	.tag-empty {
		color: #bbb;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		gap: 12rpx;
	}

	.tag-tabs {
		display: flex;
		gap: 32rpx;
		margin: 24rpx 32rpx 0 32rpx;
	}

	.tag-tab {
		font-size: 28rpx;
		color: #bbb;
		padding-bottom: 8rpx;
		border-bottom: 4rpx solid transparent;
	}

	.tag-tab.active {
		color: #fff;
		border-bottom: 4rpx solid #7bdffe;
	}

	.tag-options {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin: 24rpx 32rpx 0 32rpx;
	}

	.tag-option {
		border: 1rpx solid #888;
		border-radius: 32rpx;
		padding: 8rpx 28rpx;
		color: #fff;
		font-size: 26rpx;
		background: #23232b;
		transition: all 0.2s;
	}

	.tag-option.selected {
		border-color: #7bdffe;
		color: #7bdffe;
		background: #18181a;
	}

	.wx-row {
		margin: 32rpx 32rpx 0 32rpx;
		display: flex;
		align-items: center;
		gap: 24rpx;
	}

	.wx-label {
		font-size: 28rpx;
		color: #fff;
	}

	.wx-value {
		flex: 1;
		display: flex;
		align-items: center;
		gap: 12rpx;
		background: #23232b;
		border-radius: 16rpx;
		padding: 12rpx 24rpx;
		color: #fff;
		font-size: 28rpx;
	}

	.save-btn {
		width: 100%;
		background: linear-gradient(90deg, #7bdffe, #b97cff);
		color: #fff !important;
		font-size: 32rpx;
		border: none;
	}

	.popup-content {
		padding: 48rpx 32rpx 32rpx 32rpx;
		/* background: #23232b; */
		border-radius: 24rpx;
		min-width: 540rpx;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #222;
		margin-bottom: 32rpx;
		text-align: center;
	}

	.popup-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		margin-bottom: 32rpx;
	}

	.popup-tag {
		border: 1rpx solid #888;
		border-radius: 32rpx;
		padding: 8rpx 28rpx;
		color: #333;
		font-size: 26rpx;
		/* background: #18181a; */
		transition: all 0.2s;
	}

	.popup-tag.selected {
		border-color: #7bdffe;
		color: #7bdffe;
		/* background: #23232b; */
	}

	.avatar-wrap {
		width: 50vw;
		height: 50vw;
		max-width: 220rpx;
		max-height: 220rpx;
		border-radius: 50%;
		overflow: hidden;
		margin: 0 auto;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.avatar-upload {
		position: absolute;
		right: 10rpx;
		bottom: 10rpx;
		/* background: rgba(0, 0, 0, 0.5); */
		border-radius: 50%;
		padding: 8rpx;
	}
</style>